package gostrings

import "strings"

// RemoveAll removes all occurrences of before and after from str
func RemoveAll(str, before, after string) string {
	s, b := removeStrings(str, before, after)
	if b {
		return s
	}
	for {
		s, b = removeStrings(s, before, after)
		if b {
			return s
		}
	}
}

// RemoveFirst removes the first occurrence of before and after from str
func RemoveFirst(str, before, after string) string {
	s, _ := removeStrings(str, before, after)
	return s
}

func RemoveLast(str, before, after string) string {
	beforeIndex := strings.LastIndex(str, before)
	if beforeIndex < 0 {
		return str
	}
	start := beforeIndex + len(before)
	afterIndex := strings.Index(str[start:], after)
	if afterIndex < 0 {
		return str
	}
	if beforeIndex == 0 {
		return str[start+afterIndex+len(after):]
	}
	return str[:beforeIndex] + str[start+afterIndex+len(after):]
}

// removeStrings removes the first occurrence of before and after from str
func removeStrings(str, before, after string) (string, bool) {
	if str == EMPTY || before == EMPTY || after == EMPTY {
		return str, true
	}
	beforeIndex := strings.Index(str, before)
	if beforeIndex < 0 {
		return str, true
	}
	start := beforeIndex + len(before)
	afterIndex := strings.Index(str[start:], after)
	if afterIndex < 0 {
		return str, true
	}
	if beforeIndex == 0 {
		return str[start+afterIndex+len(after):], false
	}
	return str[:beforeIndex] + str[start+afterIndex+len(after):], false
}
